import React, { useEffect, useRef, useState } from 'react'
import { ArrowLeft, Setting } from '@nutui/icons-react'
import { Success, Cross } from '@react-vant/icons';
import { Button, Cell, Toast } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import { Popover } from 'antd-mobile'
import axios from 'axios'
import '../../App.css'

export default function Face() {
    const navigate = useNavigate()
    const [flag, setFlag] = useState(false)
    const [flag1, setFlag1] = useState(false)


    const videoRef = useRef(null);
    const canvasRef = useRef(null);
    const [capturedImages, setCapturedImages] = useState([]);

    // 隐藏警告
    const error = console.error;
    console.error = (...args) => {
        if (/defaultProps/.test(args[0])) return;
        error(...args);
    };
    //打开摄像头
    //该函数为异步函数，函数内部可以await关键字来等待异步操作的完成
    const startCamera = async () => {
        try {
            // navigator.mediaDevices.getUserMedia ({video:true}):这是Web Api中的一部分，
            //用于从用户设备获取媒体流（例如视频、音频）
            const stream = await navigator.mediaDevices.getUserMedia({ video: true });
            if (videoRef.current) { //如果videoRef.current存在
                videoRef.current.srcObject = stream
            }
        } catch (error) {
            console.log('访问摄像头出错：', error)
            //处理错误 （例如向用户显示消息）
        }
    }

    // 关闭摄像头
    const closeMedia = () => {
        //获取videoRef引用的当前<video>元素
        const video = videoRef.current;
        //获取<video>元素的srcObject属性，这是一个MediaStream对象
        const stream = video.srcObject;
        //检查stream对象是否具有getTracks方法（用于获取所有媒体轨道）
        if ('getTracks' in stream) {
            //获取媒体流中的所有轨道（例如视频轨道、音频轨道等）
            const tracks = stream.getTracks();
            tracks.forEach(track => {
                track.stop(); //停止每个轨道，释放资源（例如停止摄像头或麦克风的使用）
            });
        }
    }
    const capture = () => {
        if (!canvasRef.current || !videoRef.current) return;
            const canvas = canvasRef.current;
            const context = canvas.getContext('2d');
            //绘制图像
            //将 videoRef.current 中当前的视频帧绘制到 <canvas> 上
            context.drawImage(videoRef.current, 0, 0, canvas.width, canvas.height);

            //将 <canvas> 中的内容转换为 base64 编码的 JPEG 图像
            const imageSrc = canvas.toDataURL('image/jpeg');
            setCapturedImages([...capturedImages, imageSrc]);
            submitImages(imageSrc);
    }


    const submitImages = async (img) => {
        try {
            const res = await axios.post('http://127.0.0.1:3000/faceLogin', { b64: img });
            if (res.data.code == 200) {
                setFlag(true)
                
                setTimeout(() => {
                    setFlag(false)
                    navigate('/renzheng')
                }, 2000)
            }
            if (res.data.code == 401) {
                setFlag1(true)
                setTimeout(() => {
                    setFlag1(false)
                }, 2000)
            }
        } catch (error) {
            console.log('提交图像出错', error)
            setFlag1(true)
        }
    }

    useEffect(() => {
        startCamera();
    }, [])
    return (
        <div>
            <div className="face_header">
                <p style={{ marginTop: '15px', width: '15%' }} onClick={() => {
                    navigate('/login')
                }}><ArrowLeft /></p>
                <p style={{ width: '70%', textAlign: 'center' }}>人脸登录</p>
                <p style={{ animation: 'bounce 1s linear infinite', style: '15%' }}>
                    <img src='/smaill.png' style={{
                        width: '63px',
                        height: '50px',
                        borderRadius: '50px'
                    }} className='bounce' />
                </p>

            </div>
            <p>
                <h3 style={{ paddingLeft: '35px', display: 'block', marginTop: '10px', marginBottom: '-15px' }}>人脸登录</h3><br />
                <span style={{ fontSize: '14px', paddingLeft: '35px', color: 'red', display: flag1 ? 'block' : 'none' }}>请选择使用验证码或重新进行认证</span>
            </p>
            <div
                style={{
                    marginTop: '70px',
                    height: 'auto',
                    position: 'relative'
                }}
            >
                <Cell>
                    <div className="kl">
                        <video ref={videoRef} autoPlay muted></video>
                        <canvas ref={canvasRef} style={{ display: 'none' }}></canvas>
                    </div>


                </Cell>

                <Button onClick={capture} style={{ width: '50%', margin: '50px auto' }} color='linear-gradient(to right, rgb(78,115,223), rgb(2,167,240))' type='primary' block round>开始认证</Button>

                <div className='mask_err' style={{ display: flag1 ? 'block' : 'none' }}> <Cross style={{ color: 'black', fontSize: '60px' }} /></div>
                <div className='mask_success' style={{ display: flag ? 'block' : 'none' }}> <Success style={{ color: 'black', fontSize: '60px' }} /></div>
            </div>

            <Popover
                content={
                    <>
                        <img src='video.png' style={{ width: '45px', height: '35px', marginLeft: '20px' }} onClick={closeMedia} />
                    </>
                }
                trigger='click'
                placement='left-end'
                defaultVisible
            >
                <div style={{
                    width: '35px',
                    height: '35px',
                    position: 'fixed',
                    bottom: '70px',
                    right: '20px',
                    border: '1px solid #d5d5d5',
                    borderRadius: '50px',
                }}>
                    <Setting />
                </div>
            </Popover>
        </div>
    )
}
